#!/bin/bash

# SPAM3UK API 完整测试脚本
# 测试服务器: http://101.201.32.200:5700

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
PURPLE='\033[0;35m'
NC='\033[0m' # No Color

# 服务器配置
SERVER_HOST="101.201.32.200"
SERVER_PORT="5700"
BASE_URL="http://${SERVER_HOST}:${SERVER_PORT}"

echo "🧪 SPAM3UK API 完整测试"
echo "=================================================="
echo "测试服务器: ${BASE_URL}"
echo "测试时间: $(date)"
echo ""

# 测试结果统计
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0

# 通用测试函数
test_api() {
    local test_name="$1"
    local method="$2"
    local endpoint="$3"
    local expected_status="$4"
    local data="$5"
    
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
    echo -n "🔧 测试: $test_name ... "
    
    if [ "$method" = "GET" ]; then
        response=$(curl -s -w "%{http_code}" -o /tmp/api_response.json "$BASE_URL$endpoint" 2>/dev/null)
    elif [ "$method" = "POST" ]; then
        if [ -n "$data" ]; then
            response=$(curl -s -w "%{http_code}" -o /tmp/api_response.json -X POST -H "Content-Type: application/json" -d "$data" "$BASE_URL$endpoint" 2>/dev/null)
        else
            response=$(curl -s -w "%{http_code}" -o /tmp/api_response.json -X POST "$BASE_URL$endpoint" 2>/dev/null)
        fi
    fi
    
    status_code="${response: -3}"
    
    if [ "$status_code" = "$expected_status" ]; then
        echo -e "${GREEN}✅ PASS${NC} (HTTP $status_code)"
        PASSED_TESTS=$((PASSED_TESTS + 1))
        
        # 显示响应内容摘要
        if [ -f /tmp/api_response.json ]; then
            content_length=$(wc -c < /tmp/api_response.json)
            if [ "$content_length" -gt 0 ]; then
                echo "   📄 响应长度: ${content_length} 字节"
                # 如果是JSON，尝试解析并显示关键信息
                if jq empty /tmp/api_response.json 2>/dev/null; then
                    # 检查是否是数组
                    if jq -e 'type == "array"' /tmp/api_response.json >/dev/null 2>&1; then
                        count=$(jq length /tmp/api_response.json)
                        echo "   📊 数组长度: $count 项"
                        if [ "$count" -gt 0 ]; then
                            first_item=$(jq -r '.[0] | keys[]' /tmp/api_response.json 2>/dev/null | head -3 | tr '\n' ', ' | sed 's/,$//')
                            echo "   🔑 字段示例: $first_item"
                        fi
                    else
                        # 检查是否有常见字段
                        if jq -e '.total_count' /tmp/api_response.json >/dev/null 2>&1; then
                            total=$(jq -r '.total_count' /tmp/api_response.json)
                            echo "   📊 总数: $total"
                        fi
                        if jq -e '.data' /tmp/api_response.json >/dev/null 2>&1; then
                            data_type=$(jq -r '.data | type' /tmp/api_response.json)
                            echo "   📋 数据类型: $data_type"
                        fi
                    fi
                fi
            fi
        fi
    else
        echo -e "${RED}❌ FAIL${NC} (期望: HTTP $expected_status, 实际: HTTP $status_code)"
        FAILED_TESTS=$((FAILED_TESTS + 1))
        
        # 显示错误详情
        if [ -f /tmp/api_response.json ]; then
            echo "   🚨 错误响应:"
            head -200 /tmp/api_response.json | head -3
        fi
    fi
    echo ""
}

# 检查服务器连通性
echo "1️⃣ 服务器连通性检查"
echo "----------------------------------------"
test_api "健康检查" "GET" "/health" "200"

echo "2️⃣ 基础页面测试"
echo "----------------------------------------"
test_api "主页访问" "GET" "/" "200"
test_api "Web界面" "GET" "/web/" "200"

echo "3️⃣ 车辆信息API测试"
echo "----------------------------------------"
test_api "获取所有车辆" "GET" "/api/vehicles" "200"
test_api "分页获取车辆(第1页)" "GET" "/api/vehicles?page=1&page_size=5" "200"
test_api "分页获取车辆(第2页)" "GET" "/api/vehicles?page=2&page_size=5" "200"
test_api "兼容接口-获取所有车辆" "GET" "/api/get_all_cars" "200"

echo "4️⃣ 筛选功能测试"
echo "----------------------------------------"
test_api "按车型筛选(Focus)" "GET" "/api/vehicles?model=Focus" "200"
test_api "按制造商筛选(Ford)" "GET" "/api/vehicles?make=Ford" "200"
test_api "按燃料类型筛选(Hybrid)" "GET" "/api/vehicles?fuel_type=Hybrid" "200"
test_api "按价格范围筛选" "GET" "/api/vehicles?min_price=20000&max_price=40000" "200"
test_api "按车辆类型筛选(car)" "GET" "/api/vehicles?vehicle_type=car" "200"

echo "5️⃣ 分类功能测试"
echo "----------------------------------------"
test_api "获取分类统计" "GET" "/api/categories" "200"
test_api "混合动力分类车辆" "GET" "/api/categories/hybrid_electric/vehicles" "200"
test_api "SUV分类车辆" "GET" "/api/categories/suv_crossovers/vehicles" "200"
test_api "性能车分类车辆" "GET" "/api/categories/performance/vehicles" "200"
test_api "MPV分类车辆" "GET" "/api/categories/people_movers/vehicles" "200"

echo "6️⃣ 车型配置(Trim)功能测试"
echo "----------------------------------------"
test_api "获取Puma车型配置" "GET" "/api/get_trims?model=Puma" "200"
test_api "获取Focus车型配置" "GET" "/api/get_trims?model=Focus" "200"
test_api "获取Mustang车型配置" "GET" "/api/get_trims?model=Mustang" "200"
test_api "获取不存在车型配置" "GET" "/api/get_trims?model=NonExistent" "200"

echo "7️⃣ 单个车辆详情测试"
echo "----------------------------------------"
test_api "获取车辆详情(ID=1)" "GET" "/api/cars/1" "200"
test_api "获取车辆详情(ID=5)" "GET" "/api/cars/5" "200"
test_api "获取不存在车辆(ID=999)" "GET" "/api/cars/999" "404"

echo "8️⃣ 复合筛选测试"
echo "----------------------------------------"
test_api "多条件筛选1" "GET" "/api/vehicles?vehicle_type=car&fuel_type=Petrol&page=1&page_size=3" "200"
test_api "多条件筛选2" "GET" "/api/vehicles?min_price=25000&max_price=50000&make=Ford" "200"
test_api "多条件筛选3" "GET" "/api/vehicles?vehicle_category=performance&fuel_type=Petrol" "200"

echo "9️⃣ 边界条件测试"
echo "----------------------------------------"
test_api "空参数查询" "GET" "/api/vehicles?" "200"
test_api "无效页码(page=0)" "GET" "/api/vehicles?page=0&page_size=5" "200"
test_api "大页码查询" "GET" "/api/vehicles?page=999&page_size=5" "200"
test_api "大页面大小" "GET" "/api/vehicles?page=1&page_size=100" "200"
test_api "无效价格范围" "GET" "/api/vehicles?min_price=100000&max_price=50000" "200"

echo "🔟 数据抓取功能测试"
echo "----------------------------------------"
echo "⚠️ 注意: 数据抓取测试将实际执行抓取操作，可能需要较长时间"
read -p "是否执行数据抓取测试? (y/N): " run_scraping
if [[ $run_scraping =~ ^[Yy]$ ]]; then
    test_api "抓取Puma车型配置" "POST" "/api/scrape_trims?model=Puma" "200"
    test_api "抓取Focus车型配置" "POST" "/api/scrape_trims?model=Focus" "200"
    echo "📝 注意: 全量抓取(/api/scrape_all)测试跳过，避免长时间运行"
else
    echo "⏭️ 跳过数据抓取测试"
fi

echo ""
echo "📊 测试结果统计"
echo "=================================================="
echo -e "总测试数: ${BLUE}$TOTAL_TESTS${NC}"
echo -e "通过测试: ${GREEN}$PASSED_TESTS${NC}"
echo -e "失败测试: ${RED}$FAILED_TESTS${NC}"

success_rate=$((PASSED_TESTS * 100 / TOTAL_TESTS))
echo -e "成功率: ${CYAN}$success_rate%${NC}"

if [ $FAILED_TESTS -eq 0 ]; then
    echo -e "\n🎉 ${GREEN}所有API测试通过！服务运行正常${NC} ✨"
    exit_code=0
elif [ $success_rate -ge 90 ]; then
    echo -e "\n😊 ${YELLOW}大部分API测试通过，服务基本正常${NC}"
    exit_code=0
elif [ $success_rate -ge 70 ]; then
    echo -e "\n😐 ${YELLOW}部分API测试失败，需要检查服务状态${NC}"
    exit_code=1
else
    echo -e "\n😞 ${RED}多个API测试失败，服务可能存在问题${NC}"
    exit_code=2
fi

echo ""
echo "🔗 快速访问链接:"
echo "----------------------------------------"
echo "• 健康检查: $BASE_URL/health"
echo "• Web界面: $BASE_URL/web/"
echo "• 车辆API: $BASE_URL/api/vehicles?page=1&page_size=5"
echo "• 分类统计: $BASE_URL/api/categories"
echo "• Trim配置: $BASE_URL/api/get_trims?model=Puma"

echo ""
echo "📋 测试完成时间: $(date)"

# 清理临时文件
rm -f /tmp/api_response.json

exit $exit_code
